(define-module (luhux services games)
  #:use-module (gnu system shadow)  
  #:use-module (gnu services)
  #:use-module (gnu services shepherd)
  #:use-module (gnu packages games)
  #:use-module (gnu packages admin)  
  #:use-module (guix gexp)
  #:use-module (guix modules)
  #:use-module (guix records)
  #:use-module (ice-9 match)
  #:export (
	    minetest-configuration
	    minetest-configuration?	    
	    minetest-service-type
	    )
  )

;;
;;
;;  Minetest 游戏服务器
;;
;;

(define-record-type* <minetest-configuration>
  minetest-configuration make-minetest-configuration minetest-configuration?
  (package minetest-configuration-package
	   (default minetest))
  )

(define %minetest-accounts
  (list
   (user-account
    (name "minetest")
    (group "minetest")
    (system? #t)
    (comment "Minetest Game Server User")
    (home-directory "/var/lib/minetest")
    (shell (file-append shadow "/sbin/nologin"))
    )
   (user-group
    (name "minetest")
    (system? #t)
    )
   )
  )

(define minetest-shepherd-service
  (match-lambda
    (($ <minetest-configuration> package)
     (with-imported-modules (source-module-closure
                             '((gnu build shepherd)))
       (shepherd-service
	(documentation "Minetest Game Server User")
	(provision '(minetest))
        (modules '((gnu build shepherd)))	
	(start #~
	 (make-forkexec-constructor
	  (list #$(string-append "/run/current-system/profile" "/bin/minetest")
		"--server")
	  #:user "minetest"
	  #:group "minetest"
	  #:environment-variables
	  `("HOME=/var/lib/minetest"
	    "MINETEST_SUBGAME_PATH=/run/current-system/profile/share/minetest/games"
	    )
	  )
	 )
	(stop #~(make-kill-destructor))
	)
       )
     )
    )
  )


(define minetest-service-type
  (service-type
   (name 'minetest)
   (description
    "Run The Minetest Game Server")
   (extensions
    (list (service-extension account-service-type
			     (const %minetest-accounts))
	  (service-extension shepherd-root-service-type
			     (compose list minetest-shepherd-service))
	  (service-extension profile-service-type
			     (compose list minetest-configuration-package))
	  )
    
    )
   (default-value (minetest-configuration))
   )
  )

